<template>
  <div class="home">
    <Sidebar v-model:type="filterType" />
    <div class="home-content" @scroll="handleScroll" ref="contentRef">
      <!-- 初始加载状态 -->
      <div v-if="initialLoading" class="loading-container">
        <a-spin size="large" />
        <div class="loading-text">正在加载数据...</div>
      </div>

      <!-- 数据展示 -->
      <div v-else-if="chartList.length" class="chart-list">
        <EchartsList :chartList="chartList" @chartDeleted="handleChartDeleted" />
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-container">
        <div class="empty-text">暂无数据</div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="chartList.length && !initialLoading">
        <a-spin v-if="loadMoreLoading" />
        <span v-else-if="hasMore" class="load-more-text">下拉加载更多</span>
        <span v-else class="load-more-text">没有更多数据了</span>
      </div>

      <!-- 错误状态 -->
      <div v-if="error" class="error-container">
        <div class="error-text">{{ error }}</div>
        <a-button @click="retryLoad" type="primary">重试</a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import Sidebar from '@/components/Sidebar/index.vue'
import EchartsList from '@/components/EchartsList/index.vue'
import './index.css'
import { chartMenus } from '@/utils/chartTypes'
import { getEchartsList } from '@/utils/api'
import { ref, computed, nextTick, onMounted, watch } from 'vue'

// 过滤类型
const filterType = ref(chartMenus[0].value)

// 数据状态
const chartList = ref([])
const pagination = ref({
  page: 1,
  limit: 35,
  total: 0,
  totalPages: 0,
  hasNext: false,
  hasPrev: false
})

// 加载状态
const initialLoading = ref(false)
const loadMoreLoading = ref(false)
const error = ref('')

// 滚动容器引用
const contentRef = ref(null)

// 是否还有更多数据
const hasMore = computed(() => {
  return pagination.value.hasNext
})

// 是否可以加载更多
const canLoadMore = computed(() => {
  return hasMore.value && !loadMoreLoading.value && !initialLoading.value
})

/**
 * 获取数据
 * @param {boolean} isLoadMore - 是否为加载更多操作
 */
const fetchData = async (isLoadMore = false) => {
  try {
    // 设置加载状态
    if (isLoadMore) {
      loadMoreLoading.value = true
    } else {
      initialLoading.value = true
      error.value = ''
    }

    const params = {
      page: isLoadMore ? pagination.value.page + 1 : 1,
      limit: pagination.value.limit,
      type: filterType.value
    }

    const response = await getEchartsList(params)

    if (response.code === 200) {
      const { list, pagination: paginationData } = response.data

      if (isLoadMore) {
        // 加载更多：追加数据
        chartList.value = [...chartList.value, ...list]
      } else {
        // 初始加载或筛选：替换数据
        chartList.value = list
        // 滚动到顶部
        nextTick(() => {
          if (contentRef.value) {
            contentRef.value.scrollTop = 0
          }
        })
      }

      // 更新分页信息
      pagination.value = paginationData
    }
  } catch (err) {
    error.value = err.message || '获取数据失败'
  } finally {
    initialLoading.value = false
    loadMoreLoading.value = false
  }
}

/**
 * 加载更多数据
 */
const loadMore = async () => {
  if (!canLoadMore.value) return
  await fetchData(true)
}

/**
 * 重试加载
 */
const retryLoad = () => {
  fetchData()
}

/**
 * 处理滚动事件
 */
const handleScroll = async () => {
  if (!canLoadMore.value) return

  const container = contentRef.value
  if (!container) return

  // 检查是否滚动到底部附近（距离底部50px以内）
  const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 50

  if (isNearBottom) {
    await loadMore()
  }
}

/**
 * 处理图表删除事件
 * @param {string|number} chartId - 被删除的图表ID
 */
const handleChartDeleted = (chartId) => {
  // 从当前列表中移除被删除的图表
  chartList.value = chartList.value.filter((chart) => chart.id !== chartId)

  // 如果当前页面没有数据了，且不是第一页，则重新加载数据
  if (chartList.value.length === 0 && pagination.value.page > 1) {
    fetchData()
  }
}

// 监听过滤类型变化，重新获取数据
watch(filterType, () => {
  fetchData()
})

// 组件挂载时获取初始数据
onMounted(() => {
  fetchData()
})
</script>
